package com.ca.ridersclubapplication;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.data.entity.ListEntity;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.PaperCardDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.adapter.PaperAdapter;
import com.ca.ridersclubapplication.util.KeyBoardUtil;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.bar.SearchBar;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends ImmersiveActivity {

    private SearchBar searchBar;
    private RecyclerView rv;
    private final PaperAdapter adapter = new PaperAdapter(this, null);

    private TextView emptyView;

    private static String lastKeyword = "";
    private static String keyword = "";
    private static Long startId = 0L;
    private static boolean canRequest = true;
    private ProgressBar progressBar;

    private CallbackView callbackView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        //  初始化视图
        initView();

        //  动画
        transition();

        //  事件监听
        initListener();
    }

    private void initView() {

        //  搜索栏
        searchBar = findViewById(R.id.bar_search);
        //  输入框自动获取焦点
        KeyBoardUtil.showSoftInput(this, searchBar.input);
        //  设置键盘回车键为搜索功能键
        searchBar.input.setImeOptions(EditorInfo.IME_ACTION_SEARCH);

        //  空数据视图
        emptyView = findViewById(R.id.tv_empty);
        emptyView.setVisibility(View.GONE);

        //  文章列表视图
        rv = findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(adapter);

        //  文章列表视图需要根据请求到的数据更新，因此需要在数据处理器中放入待更新的视图控件
        callbackView = new CallbackView() {
            @Override
            public void update() {
                //  获取数据
                Handleable data = DataHandler.getData("PaperList:Keyword");
                if (data instanceof ListEntity<?>) {
                    //  当数据更新时（请求到了新的文章），需要追加数据
                    ListEntity<?> list = (ListEntity<?>) data;
                    List<PaperCardDto> tempList = new ArrayList<>();
                    for (Handleable h : list.getList()) {
                        if (h instanceof PaperCardDto) {
                            PaperCardDto paperDto = (PaperCardDto) h;
                            tempList.add(paperDto);
                        }
                    }

                    //  如果上次发起请求的关键词与这次的一样，则追加数据，否则重新设置数据
                    if (lastKeyword.equals(keyword)) {
                        adapter.appendList(tempList);
                    } else {
                        adapter.setList(tempList);
                    }

                    //  如果列表为空则显示无内容提示
                    emptyView.setVisibility(adapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);

                    //  记录本次请求的关键词
                    lastKeyword = keyword;
                }
            }
        };
        DataHandler.putView("PaperList:Keyword", callbackView);

        //  进度条
        progressBar = findViewById(R.id.bar_progress);

        keyword = "";
        lastKeyword = "";
        startId = 0L;
    }

    private void transition() {
        searchBar.setTransitionName("bar:search");
    }

    private void initListener() {

        //  搜索框返回按钮点击
        searchBar.backView.setOnClickListener(v -> {
            finishAfterTransition();
        });

        //  设置键盘搜索键事件
        searchBar.input.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    //  收起键盘
                    KeyBoardUtil.closeKeyBoard(SearchActivity.this, searchBar.input);
                    //  发起请求
                    requestSearch();
                }
                return false;
            }
        });

        //  搜索按钮点击
        searchBar.searchView.setOnClickListener(v -> {
            requestSearch();
        });

        //  文章列表下拉请求更多
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                //  判断关键词是否为空
                keyword = searchBar.input.getText().toString();
                if (keyword.trim().isEmpty()) {
                    return;
                }

                //  滑动到底部则加载新的文章数据
                if (!rv.canScrollVertically(1)) {

                    //  显示加载动画
                    progressBar.setVisibility(View.VISIBLE);
                    //  请求数据
                    if (canRequest) {
                        canRequest = false;
                        PaperRequester.listPaperByKeyword(SearchActivity.this, keyword, startId, new AfterExecutor<List<PaperCardDto>>() {
                            @Override
                            public void execute(Result<List<PaperCardDto>> result) {

                                List<PaperCardDto> data = result.getData();
                                //  记录本次请求的开始ID
                                if (data != null && data.size() > 0) {
                                    startId = data.get(0).getId();
                                }

                                //  关闭加载动画
                                progressBar.setVisibility(View.GONE);
                                //  开启允许请求
                                canRequest = true;
                            }
                        });
                    }
                }
            }
        });
    }

    private void requestSearch() {

        //  获取关键词
        keyword = searchBar.input.getText().toString();
        if (keyword.trim().isEmpty()) {
            Toast.makeText(this, "请输入关键词", Toast.LENGTH_SHORT).show();
            return;
        }

        if (lastKeyword.equals(keyword)) {
            return;
        }
        startId = 0L;

        //  清除文章列表
        adapter.setList(new ArrayList<>());

        //  开启加载动画
        progressBar.setVisibility(View.VISIBLE);
        //  关闭允许请求
        canRequest = false;
        //  发起请求
        PaperRequester.listPaperByKeyword(SearchActivity.this, keyword, startId, new AfterExecutor<List<PaperCardDto>>() {
            @Override
            public void execute(Result<List<PaperCardDto>> result) {
                //  关闭加载动画
                progressBar.setVisibility(View.GONE);
                //  开启允许请求
                canRequest = true;

                List<PaperCardDto> data = result.getData();

                //  记录本次请求的开始ID
                if (data != null && data.size() > 0) {
                    startId = data.get(0).getId();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataHandler.removeView("PaperList:Keyword", callbackView);
    }
}